<template>
  <div class="app-container">
    <el-card>
      <el-card
        class="filter-container"
        shadow="never"
      >
        <div>
          <i class="el-icon-search"></i>
          <span>筛选搜索</span>
          <el-button
            style="float:right"
            type="primary"
            @click="handleSearchList()"
            size="small"
          >
            查询搜索
          </el-button>
          <el-button
            style="float:right;margin-right: 15px"
            @click="handleResetSearch()"
            size="small"
          >
            重置
          </el-button>
        </div>
        <div style="margin-top: 15px">
          <el-form
            :inline="true"
            :model="listQuery"
            size="small"
            label-width="140px"
          >
            <el-form-item label="场馆名称：">
              <el-input
                v-model="listQuery.siteName"
                class="input-width"
                placeholder="场馆名称"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      <el-card
        class="operate-container"
        shadow="never"
      >
        <i class="el-icon-tickets"></i>
        <span>数据列表</span>
        <br>
        <br>
        <span>机构名称：<span>{{ this.deptName }}</span></span>
        <el-button
          size="mini"
          class="btn-add"
          @click="handleAdd()"
        >新增场馆</el-button>
      </el-card>
      <div class="table-container">
        <el-table
          ref="adminTable"
          :data="list1"
          style="width: 100%;"
          v-loading="listLoading"
          border
        >
          <el-table-column
            label="场馆名称"
            align="center"
          >
            <template slot-scope="scope">{{ scope.row.siteName }}</template>
          </el-table-column>
          <el-table-column
            label="省市"
            align="center"
          >
            <template slot-scope="scope">{{ scope.row | setAdrInfo }}</template>
          </el-table-column>
          <el-table-column
            label="详细地址"
            align="center"
            width="200"
          >
            <template
              slot-scope="scope"
              width="200"
            >{{ scope.row.siteAdd }}</template>
          </el-table-column>
          <el-table-column
            label="有效期"
            align="center"
            width="350"
          >
            <template
              slot-scope="scope"
              width="350"
            >{{ scope.row.startTime | formatDateTime }} 到 {{ scope.row.endTime | formatDateTime }}</template>
          </el-table-column>
          <el-table-column
            label="电话"
            width="140"
            align="center"
          >
            <template
              slot-scope="scope"
              width="140"
            >{{ scope.row.phone }}</template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="200"
            align="center"
          >
            <template
              slot-scope="scope"
              width="200"
            >
              <el-button
                size="mini"
                type="text"
                @click="umsDeptGet(scope.$index, scope.row)"
              >
                查看
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleUpdate(scope.$index, scope.row)"
              >
                编辑
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="handelDel(scope.$index, scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes,prev, pager, next,jumper"
          :current-page.sync="listQuery.pageNum"
          :page-size="listQuery.pageSize"
          :page-sizes="[10,15,20]"
          :total="total"
          style="margin-bottom: 20px"
        >
        </el-pagination>
      </div>
    </el-card>
    <el-dialog
      :title="isEdit?'编辑数据':'新增数据'"
      :visible="dialogVisible"
      @close="closedialogVisible"
      width="500px"
    >
      <el-form
        :model="admin"
        :rules="rules"
        ref="courseFrom"
        label-width="100px"
        size="small"
      >
        <el-form-item
          label="场馆名称："
          prop="siteName"
        >
          <el-input
            v-model="admin.siteName"
            class="input-width"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="省市区："
          required
        >
          <single-address
            ref="singleAddress"
            class="input-width"
          ></single-address>
        </el-form-item>
        <el-form-item
          label="详细地址："
          prop="siteAdd"
        >
          <el-input
            v-model="admin.siteAdd"
            class="input-width"
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="定位信息："
          prop="longitude"
        >
          <el-col
            :span="8"
            style="display: flex"
          >
            <span style="width:50px">经度</span>
            <el-input
              v-model="admin.longitude"
              class="input-width"
            ></el-input>
          </el-col>
          <el-col
            :span="8"
            style="display: flex;margin-left:10px"
          >
            <span style="width:50px">纬度</span>
            <el-input
              v-model="admin.latitude"
              class="input-width"
            ></el-input>
          </el-col>
          <el-button
            style="margin-left:10px"
            @click="getAdd"
          >获取坐标</el-button>
        </el-form-item>
        <el-form-item
          label="有效期："
          prop="dateRange"
          required
        >
          <el-date-picker
            v-model="admin.dateRange"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="dateRangeChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="联系电话："
          prop="phone"
        >
          <el-input
            v-model="admin.phone"
            class="input-width"
          ></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          @click="closedialogVisible"
          size="small"
        >取消</el-button>
        <el-button
          type="primary"
          @click="handleDialogConfirm()"
          size="small"
        >确定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="地址定位"
      :visible="mapVisible"
      @close="mapVisible = false"
      width="50%"
    >
      <div class="amap-page-container">
        <el-amap-search-box
          class="search-box"
          :search-option="searchOption"
          :on-search-result="onSearchResult"
        ></el-amap-search-box>
        <el-amap
          vid="amapDemo"
          :center="mapCenter"
          :zoom="12"
          class="amap-demo"
          :events="events"
        >
          <div class="toolbar">
            position: [{{ lng }}, {{ lat }}] address: {{ address }}
          </div>
          <!--<el-amap-marker-->
          <!--v-for="(marker,index) in markers"-->
          <!--:key="index"-->
          <!--:position="marker"-->
          <!--@tap="getMarkers(index)"-->
          <!--&gt;</el-amap-marker>-->
        </el-amap>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="mapVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="setLoaddress()"
        >确 定</el-button>
      </span>
    </el-dialog>
    <el-row
      type="flex"
      justify="end"
      style="margin-top: 20px"
    >
      <el-col :span="2">
        <el-button @click="back">返回</el-button>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { siteList, saveSite, updateSite, siteDelete } from '@/api/servDept'
// import SingleAddress from '@/components/SingleAddress'
import { formatDate } from '@/utils/date'
import moment from 'moment'
import SingleAddress from '@/components/SingleAddress'

const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  deptId: ''
}
const umsData = {
  siteName: '',
  province: '',
  city: '',
  latitude: '',
  longitude: '',
  siteAdd: '',
  startTime: '',
  endTime: '',
  phone: '',
  dateRange: []
  // businessHours: '',
  // closingTime: '',
  // createTime: '',
  // deptId: 0,
  // deptName: '',
  // id: 0,
  //
  // license: '',
  // responsible: '',
  // siteDesc: '',
  // siteImg: '',
  // siteType: '',
  // status: '',
  // updateTime: '',
}
export default {
  components: { SingleAddress },
  data () {
    const self = this
    return {
      mapVisible: false,
      deptName: '',
      list1: [],
      id: 0,
      addUms: false,
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      listLoading: false,
      dialogVisible: false,
      admin: Object.assign({}, umsData),
      isEdit: false,
      status: {
        '01': '未开始',
        '02': '合作中',
        '03': '已停止'
      },
      rules: {
        siteName: [
          { required: true, message: '请输入', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '长度在 2 到 20 个字符',
            trigger: 'blur'
          }
        ],
        dateRange: [
          { type: 'array', required: true, message: '请选择', trigger: 'blur' }
        ],
        siteAdd: [{ required: true, message: '请选择地址', trigger: 'blur' }],
        longitude: [{ required: true, message: '请输入坐标', trigger: 'blur' }],
        latitude: [{ required: true, message: '请输入坐标', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入电话号码', trigger: 'blur' }]
      },

      markers: [],
      searchOption: {
        city: '北京',
        citylimit: true
      },
      mapCenter: [116.3968789, 39.9060375],
      address: '',
      events: {
        click (e) {
          const { lng, lat } = e.lnglat
          self.lng = lng
          self.lat = lat

          // 这里通过高德 SDK 完成。
          var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          })
          geocoder.getAddress([lng, lat], function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                self.address = result.regeocode.formattedAddress
                self.$nextTick()
              }
            }
          })
        }
      },
      lng: 0,
      lat: 0
    }
  },
  created () {
    this.getList()
    this.deptName = this.$route.query.deptName
  },
  filters: {
    formatDateTime (time) {
      if (time == null || time === '') {
        return 'N/A'
      }
      const date = new Date(time)
      return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
    },
    setAdrInfo (row) {
      const { province, city, area } = row
      if (province && province.indexOf('{') !== -1) {
        return `${JSON.parse(province).provName}-${JSON.parse(city).cityName}-${area && (JSON.parse(area).countyName) || ''}`
      } else {
        return ''
      }
    }
  },
  methods: {
    getAdd () {
      this.mapVisible = true
    },
    dateRangeChange (e) {
      this.admin.startTime = moment(e[0]).format()
      this.admin.endTime = moment(e[1]).format()
      this.admin.dateRange = [this.admin.startTime, this.admin.endTime]
    },
    handleAdd () {
      this.admin = Object.assign({}, umsData)
      setTimeout(() => {
        this.$refs.singleAddress.init()
        this.$refs.singleAddress.reset(true)
      }, 10)
      this.dialogVisible = true
      this.isEdit = false
      this.addUms = true
    },
    closedialogVisible () {
      this.dialogVisible = false
      this.addUms = false
    },
    handleDialogConfirm () {
      this.$refs['courseFrom'].validate((valid) => {
        if (valid) {
          this.listLoading = true

          const {
            provCode,
            provName,
            cityCode,
            cityName,
            countyCode,
            countyName
          } = this.$refs.singleAddress.getProdReleaseAreaList()[0]
          const addrInfo = {
            province: JSON.stringify({ provCode, provName }),
            city: JSON.stringify({ cityCode, cityName }),
            area: JSON.stringify({ countyCode, countyName })
          }

          this.admin.deptName = this.deptName
          this.admin.deptId = this.$route.query.id

          const params = {
            ...this.admin,
            ...addrInfo
          }

          delete params.status_val
          delete params.status

          if (!this.addUms) {
            updateSite(params).then((response) => {
              this.dialogVisible = false
              this.listLoading = false
              this.$message({
                message: response.message,
                type: 'success'
              })
              this.addUms = false
              this.getList()
            })
          } else {
            saveSite(params).then((response) => {
              this.dialogVisible = false
              this.listLoading = false
              this.$message({
                message: response.message,
                type: 'success'
              })
              this.addUms = false
              this.getList()
            })
          }
        } else {
          this.$message({
            message: '验证失败',
            type: 'error',
            duration: 1000
          })
          return false
        }
      })
    },
    handleResetSearch () {
      this.listQuery = Object.assign({}, defaultListQuery)
    },
    handleSearchList () {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleSizeChange (val) {
      this.listQuery.pageNum = 1
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.listQuery.pageNum = val
      this.getList()
    },
    umsDeptGet (index, row) {
      this.$router.push({ path: '/dept-ms/detailVen', query: { id: row.id } })
    },
    handleUpdate (index, row) {
      const { province, city, area } = row
      setTimeout(() => {
        this.$refs.singleAddress.reset(true)
        this.$refs.singleAddress.init({
          ...JSON.parse(province),
          ...JSON.parse(city),
          ...JSON.parse(area)
        })
        this.$refs.singleAddress.setDefValue([
          JSON.parse(province).provCode,
          JSON.parse(city).cityCode,
          JSON.parse(area).countyCode
        ])
      }, 10)
      this.admin = Object.assign(this.admin, row)
      this.admin.dateRange = [this.admin.startTime, this.admin.endTime]
      this.dialogVisible = true
      this.isEdit = true
      this.addUms = false
      this.getList()
    },
    handelDel (index, row) {
      this.del(row)
    },
    del (row) {
      this.$confirm('是否要确认?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          id: row.id,
          deptId: row.deptId,
          deptName: row.deptName,
          startTime: row.startTime,
          endTime: row.endTime,
          siteName: row.siteName,
          province: row.province,
          city: row.city,
          siteAdd: row.siteAdd,
          status: '02'
        }
        siteDelete(data).then((response) => {
          this.$message({
            message: '删除成功！',
            type: 'success'
          })
          this.dialogVisible = false
          this.getList()
        })
      })
    },
    // del(index, row) {
    //   this.$confirm("是否要确认?", "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   }).then(() => {
    //     siteDelete({ id: row.id }).then((response) => {
    //       this.$message({
    //         message: "删除成功！",
    //         type: "success",
    //       });
    //       this.dialogVisible = false;
    //       this.getList();
    //     });
    //   });
    // },
    getList () {
      this.listLoading = true
      this.listQuery.deptId = this.$route.query.id
      siteList(this.listQuery).then((response) => {
        this.listLoading = false
        this.list = response.data.list.map((item) => {
          item.cityName = '北京'
          return item
        })
        this.total = response.data.total
        // this.deptName = this.list[0].deptName
        this.list1 = this.list.map((item) => {
          var status1 = item.status
          item.status_val = this.status[status1]
          return item
        })
      })
    },
    onSearchResult (pois) {
      let latSum = 0
      let lngSum = 0
      if (pois.length > 0) {
        pois.forEach((poi) => {
          const { lng, lat } = poi
          lngSum += lng
          latSum += lat
          this.markers.push([poi.lng, poi.lat])
        })
        const center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        }
        this.mapCenter = [center.lng, center.lat]
        this.lng = this.mapCenter[0]
        this.lat = this.mapCenter[1]
      }
    },
    setLoaddress () {
      this.mapVisible = false
      // this.admin.siteAdd = this.address
      this.admin.longitude = this.lng
      this.admin.latitude = this.lat
    },
    back () {
      this.$router.go(-1)
    }
  }
}
</script>
<style>
.el-date-editor .el-range-separator {
  padding: 0 5px;
  /*line-height: 32px;*/
  width: 15%;
  color: #303133;
}
.el-date-editor--daterange.el-input__inner {
  width: 100%;
}

.amap-demo {
  width: 100%;
  height: 300px !important;
}

.search-box {
  position: absolute;
  top: 25px;
  left: 20px;
}

.amap-page-container {
  position: relative;
}
</style>
